﻿using HarmonyLib;
using RimWorld;
using RimWorld.Planet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Verse;
using Verse.AI;
using MVCF;
using MVCF.Utilities;

namespace Miao.Stand
{/// <summary>
/// 绘制替身需要的额外面板
/// </summary>
    [HarmonyPatch(typeof(Pawn_DraftController), "GetGizmos")]//获取画Gizmos
    public class Pawn_DraftController_GetGizmos
    {
        public static void Postfix(ref IEnumerable<Gizmo> __result, Pawn_DraftController __instance)
        {
            //List<Gizmo> gizmoList = __result.ToList();
            //gizmoList.Add(StandGizmo(__instance));
            //__result = gizmoList;
            //if (__instance.pawn.Faction != null && __instance.pawn.Faction.IsPlayer)
            //{
            //    __result.AddItem(StandGizmo(__instance));
            //}
            if (__instance.pawn.story.traits.HasTrait(StandDefOf.StandMaster))//如果有替身特性
            {
                //StandWorldSave standWorldSave = StandWorldSave.Instance;
                //StandData standData = standWorldSave.Get(__instance.pawn.ThingID);//读取对应替身类按钮数据

                StandMasterHediff standHediff = __instance.pawn.GetStandHediff();
                //StandMasterHediff standHediff = GetStandHediff(__instance.pawn);
                Gizmo standActiveGizmo = StandActiveGizmo(__instance.pawn, standHediff);
                __result = __result.AddItem(standActiveGizmo);


                if (standHediff.stand.Spawned)
                {
                    Gizmo standFollowGizmo = StandFollow(standHediff.stand);
                    __result = __result.AddItem(standFollowGizmo);
                    if (__instance.pawn.drafter.Drafted)
                    {
                        Gizmo standAttackGizmo = StandAttackGizmo(__instance);
                        __result = __result.AddItem(standAttackGizmo);

                        Gizmo standTakeGizmo = StandTakeGizmo(__instance);
                        __result = __result.AddItem(standTakeGizmo);

                        var standGizmos = standHediff.stand.GetDraftedStandGizmos();
                        if (standGizmos != null)
                        {
                            __result = __result.Concat(standGizmos);
                        }
                    }
                }
            }
        }

        private static Gizmo StandActiveGizmo(Pawn owner, StandMasterHediff standHediff)
        {
            //StandWorldSave standWorldSave = Find.World.GetComponent<StandWorldSave>();

            Command_Toggle command_Toggle = new Command_Toggle
            {
                defaultLabel = "替身".Translate(),
                defaultDesc = "这是召唤替身的按钮".Translate(),
                //disabledReason = "无法有效呼吸".Translate(),//无效原因
                icon = Stand.ModSingleton.LoadIcon("替身召唤"),
                Disabled = false,
                Order = 15,//用于绘制顺序
                turnOnSound = SoundDefOf.DraftOn,
                turnOffSound = SoundDefOf.DraftOff,
                //groupKey = 114514,
                isActive = () => { return standHediff.stand.Spawned; },
                //isActive = () => {return standData.ActiveStand; },
                toggleAction = () =>
                {
                    if (!standHediff.stand.Spawned)
                    {
                        standHediff.ActiveStand(owner.Position, owner.Map);
                    }
                    else
                    {
                        standHediff.InactiveStand();
                    }
                    ////standData.ActiveStand = !standData.ActiveStand;
                    //if (standData.ActiveStand)
                    //{
                    //    standHediff.ActiveStand(__instance.pawn.Position, __instance.pawn.Map);
                    //    //StandGenerator.CreateStandPawn(__instance.pawn, __instance.pawn.Position, __instance.pawn.Map, __instance.pawn.Faction);
                    //}
                    //else
                    //{
                    //    standHediff.InactiveStand();
                    //}
                    //Messages.Message("替身已放出", MessageTypeDefOf.NeutralEvent);
                }
            }; //command_Toggle.hotKey = KeyBindingDefOf.Command_ColonistDraft;热键
            if (owner.Downed)//倒地不可召唤
            {
                command_Toggle.Disable("IsIncapped".Translate(owner.LabelShort, owner));
            }
            return command_Toggle;
        }
        /// <summary>
        /// 替身采取跟随模式，还是自由移动，并攻击进入范围内的有威胁单位
        /// </summary>
        /// <param name="owner"></param>
        /// <returns></returns>
        private static Gizmo StandFollow(StandPawn stand)
        {
            Command_Toggle command_Toggle = new Command_Toggle//僵尸Mod的替换用的是Command_Action，每次按下进行图片替换，如果将来要将替身行为扩展成枚举我也可以这么做
            {
                defaultLabel = "背后灵".Translate(),
                defaultDesc = "替身是出现在背后，还是处于游荡并自动攻击敌人状态".Translate(),
                //disabledReason = "无法有效呼吸".Translate(),//无效原因
                icon = Stand.ModSingleton.LoadIcon("背后灵"),
                Disabled = false,
                Order = 15.1f,//用于绘制顺序
                turnOnSound = SoundDefOf.DraftOn,
                turnOffSound = SoundDefOf.DraftOff,
                //groupKey = 114514,
                isActive = () => { return stand.ghostFollow; },
                //isActive = () => {return standData.ActiveStand; },
                toggleAction = () =>
                {
                    stand.ghostFollow = !stand.ghostFollow;
                }
            };
            return command_Toggle;

        }
        private static Gizmo StandAttackGizmo(Pawn_DraftController __instance)
        {
            Command_StandRadiusTargetSimple command_Target = new Command_StandRadiusTargetSimple();
            command_Target.defaultLabel = "替身攻击".Translate();
            command_Target.defaultDesc = "让替身对目标进行攻击".Translate();
            command_Target.icon = Stand.ModSingleton.LoadIcon("替身攻击");
            command_Target.hotKey = KeyBindingDefOf.Misc8;
            command_Target.Order = 15.2f;
            command_Target.targetingParams = TargetingParameters.ForAttackAny();
            command_Target.standPawn = MasterGetStandPawn(__instance.pawn);
            command_Target.action = ChoseTarget;
            command_Target.showAttackRange = true;
            void ChoseTarget(LocalTargetInfo localTargetInfo)//这个是Targeter选中的目标
            {

                Verb v = command_Target.standPawn.TryGetAttackVerb(localTargetInfo.Thing);//就是在MVCF框架中重写了获得攻击的方式，现在确实是优先获取远程
                v.OrderForceTarget(localTargetInfo.Thing);
                v.castCompleteCallback += () =>
                {
                    //Messages.Message("确定攻击调用次数",MessageTypeDefOf.NegativeEvent);只会固定调用一次，安心吧。
                    if (!v.IsMeleeAttack&& command_Target.standPawn.ghostFollow)
                    {
                        command_Target.standPawn.SetStandGhostPos();
                    }
                };


                //Find.Targeter.OrderPawnForceTarget(target);//这样写绕路了，但也可以执行动作。
                //}
            }
            //command_Target.targetingParams.canTargetLocations = AllSelectedColonistsCanTargetLocations();
            return command_Target;
        }


        /// <summary>
        /// 拿取东西到主人库存或携带Pawn在身旁
        /// </summary>
        public static Gizmo StandTakeGizmo(Pawn_DraftController __instance)
        {
            Command_StandRadiusTargetSimple command_Target = new Command_StandRadiusTargetSimple();
            command_Target.defaultLabel = "替身拿取".Translate();
            command_Target.defaultDesc = "让替身去拿去物品或携带单位".Translate();
            command_Target.icon = Stand.ModSingleton.LoadIcon("替身拿取");
            command_Target.hotKey = KeyBindingDefOf.Misc9;
            command_Target.Order = 15.3f;
            command_Target.standPawn = MasterGetStandPawn(__instance.pawn);
            //command_Target.targetingParams = TargetingParameters.ForDraftedCarryTransporter(__instance.pawn);
            command_Target.targetingParams = new TargetingParameters()
            {
                //canTargetLocations = true,
                canTargetItems = true,
                canTargetPawns = true,
                canTargetBuildings = false,
                canTargetAnimals = true,
                canTargetHumans = true,
                canTargetPlants = false,
                mustBeSelectable = true,
                mapObjectTargetsMustBeAutoAttackable = false,
                thingCategory = ThingCategory.Item,//重要的
            };

            command_Target.action = ChoseTarget;
            void ChoseTarget(LocalTargetInfo localTargetInfo)
            {


                if (localTargetInfo.Thing.def.category == ThingCategory.Item)
                {

                    //if (command_Target.standPawn.HasBeghavior(localTargetInfo.Thing))
                    //{
                    //Job job = JobMaker.MakeJob(JobDefOf.HaulToTransporter, localTargetInfo, command_Target.standPawn.owner);//是不是点A到点B的意思？
                    Job job = JobMaker.MakeJob(JobDefOf.HaulToContainer, localTargetInfo, command_Target.standPawn.owner);//是不是点A到点B的意思？
                    job.count = 75;//代表可搬运数量
                    job.ignoreForbidden = true;
                    //HaulAIUtility
                    command_Target.standPawn.jobs.TryTakeOrderedJob(job, JobTag.Misc);
                    //}
                }
                else if (localTargetInfo.Thing.def.category == ThingCategory.Pawn)//如果携带东西比较慢，是因为设计就设计成携带时速度会*=0.6f
                {
                    Job job = JobMaker.MakeJob(JobDefOf.CarryDownedPawnDrafted, localTargetInfo);
                    job.count = 75;//好像代表可搬运数量
                    job.ignoreForbidden = true;//无视禁止
                    command_Target.standPawn.jobs.TryTakeOrderedJob(job, JobTag.Misc);
                }

            }
            return command_Target;
        }


        private static StandPawn MasterGetStandPawn(Pawn pawn)
        {
            for (int i = 0; i < pawn.health.hediffSet.hediffs.Count; i++)
            {
                if (pawn.health.hediffSet.hediffs[i] is StandMasterHediff)//用了一个很搞的方式，来让Hediff实际上是HediffDef来互通。
                {
                    return (pawn.health.hediffSet.hediffs[i] as StandMasterHediff).stand;
                }
            }
            return null;
        }

        //private static Gizmo StandAttackGizmo(Pawn_DraftController __instance, StandData standData)
        //{
        //    Command_Target command_Target = new Command_Target();
        //    command_Target.defaultLabel = "替身攻击".Translate();
        //    command_Target.defaultDesc = "用于替身攻击".Translate();
        //    command_Target.icon = TexCommand.SquadAttack;
        //    command_Target.hotKey = KeyBindingDefOf.Misc8;
        //    command_Target.targetingParams = TargetingParameters.ForAttackAny();
        //    command_Target.targetingParams.canTargetLocations = AllSelectedColonistsCanTargetLocations();

        //    command_Target.action = (LocalTargetInfo target) =>
        //    {
        //        foreach (Pawn item in Find.Selector.SelectedObjects.Where(delegate (object x)
        //        {
        //            Pawn pawn2 = x as Pawn;
        //            return pawn2 != null && pawn2.IsColonistPlayerControlled && pawn2.Drafted;
        //        }).Cast<Pawn>())
        //        {
        //            string failStr2;
        //            Action attackAction = FloatMenuUtility.GetAttackAction(item, target, out failStr2);
        //            if (attackAction != null)
        //            {
        //                attackAction();
        //            }
        //            else if (!failStr2.NullOrEmpty())
        //            {
        //                Messages.Message(failStr2, target.Thing, MessageTypeDefOf.RejectInput, historical: false);
        //            }
        //        }
        //    };


        //    return command_Target;
        //}
        ///// <summary>
        ///// 所有选定的殖民者都可以锁定目标位置，抄PawnAttackGizmoUtility
        ///// </summary>
        ///// <returns></returns>
        //private static bool AllSelectedColonistsCanTargetLocations()
        //{
        //    foreach (object selectedObject in Find.Selector.SelectedObjects)
        //    {
        //        Pawn pawn;
        //        if ((pawn = selectedObject as Pawn) != null && pawn.IsColonistPlayerControlled && pawn.Drafted)
        //        {
        //            if (pawn.equipment.Primary == null || pawn.equipment.PrimaryEq.PrimaryVerb.verbProps.IsMeleeAttack)
        //            {
        //                return false;
        //            }
        //            if (!pawn.equipment.PrimaryEq.PrimaryVerb.verbProps.targetParams.canTargetLocations)
        //            {
        //                return false;
        //            }
        //        }
        //    }
        //    return true;
        //}

        static StandMasterHediff GetStandHediff(Pawn target)//因为没有添加Trait时添加Hediff的回调，所以只能这么写，只是召唤时的判定，性能应该还好
        {
            //if (target.story.traits.HasTrait(CustomDefOf.Stand))
            //{
            HediffSet hediffSet = target.health.hediffSet;
            StandMasterHediff standHediff;
            for (int i = 0; i < hediffSet.hediffs.Count; i++)
            {
                if (hediffSet.hediffs[i] is StandMasterHediff)//用了一个很搞的方式，来让Hediff实际上是HediffDef来互通。
                {
                    standHediff = (StandMasterHediff)hediffSet.hediffs[i];
                    if (standHediff.stand == null)
                    {
                        Messages.Message("错误的情况下并重新创建了替身", MessageTypeDefOf.NeutralEvent);
                        var standPawnKind = StandGenerator.standTuples.RandomElement().standPawnKindDef;
                        standHediff.stand = StandGenerator.CreateStandPawn(standPawnKind, standHediff.pawn);
                    }
                    return standHediff;
                }
            }
            //如果没有StandHdiff则创建替身调用
            standHediff = StandGenerator.StandHediffGenerator(target);
            return standHediff;
        }
    }
}
